package cn.itsource.basic.service.impl;

import cn.itsource.basic.config.BussinessException;
import cn.itsource.basic.constant.BaseConstant;
import cn.itsource.basic.dto.PhoneSmsCodeDto;
import cn.itsource.basic.service.IVerifyCodeService;
import cn.itsource.basic.util.SendSmsUtil;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.basic.util.VerifyCodeUtils;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;



    /**
     * 获取图形验证码
     * @param uuidKey
     * @return
     */
    @Override
    public String getImageCode(String uuidKey) {
        // 生成随机数
        String randomCode = StrUtils.getComplexRandomString(4);
        // 存入到reids
        redisTemplate.opsForValue().set(uuidKey,randomCode,3, TimeUnit.MINUTES);
        // 生成图形验证码返回给前端
        return VerifyCodeUtils.VerifyCode(100, 35, randomCode);
    }

    /**
     * 发送手机验证码
     * @param dto
     */

    @Override
    public void smsCode(PhoneSmsCodeDto dto) {
        if ("register".equals(dto.getType())){
            // 验证参数是否为空
            // todo 手机号格式自己验证
            // 图形验证码是否正确
            verifyImgageCode(dto);
            // 两次发送短信间隔是否大于60s
            sendSmsCode(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE,dto.getPhone()));
        }else if ("binder".equals(dto.getType())){
            sendSmsCode(String.format(BaseConstant.VerfityCodeCons.BINDER_SMSCODE_PHONE,dto.getPhone()));
        }
    }

    private void sendSmsCode(String redisKey) {
        // redis中 key：register:smscode:phone  value：验证码:时间戳
        String redisSmsCode = (String) redisTemplate.opsForValue().get(redisKey);
        String smsCode = "";
        if (StringUtils.isNotBlank(redisSmsCode)){
//            Long expire = redisTemplate.getExpire(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()), TimeUnit.MINUTES);
//            if (expire >= 4){
//                throw new BussinessException("滚！");
//            }
            // 不为空才做 60s校验  redisSmsCode 存的是 验证码:时间戳
            String[] split = redisSmsCode.split(":");
            smsCode = split[0];
            // 当前时间
            long newTime = System.currentTimeMillis();
            // reids中的时间
            long oldTime = Long.valueOf(split[1]);
            if (newTime - oldTime < 60 * 1000){
                throw new BussinessException("滚！");
            }
        }else {
            // 生成验证码
            smsCode = StrUtils.getRandomString(4);
        }
        log.info("验证码为：{}",smsCode);
        String redisValue = smsCode+":"+ System.currentTimeMillis();
        // 存入到reids
        redisTemplate.opsForValue().set(redisKey,redisValue,5,TimeUnit.MINUTES);
        // 发送短信
//        SendSmsUtil.send(dto.getPhone(),"你好：你的验证码为："+smsCode+"，5分钟内有效！");
    }

    private void verifyImgageCode(PhoneSmsCodeDto dto) {
        String imageCode = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (StringUtils.isBlank(imageCode) || !imageCode.equalsIgnoreCase(dto.getImageCodeValue())){
             throw new BussinessException("图形验证码错误！");
        }
        // 当前手机号是否已经注册了
        User user = userMapper.findByPhone(dto.getPhone());
        if (null != user){
            throw new BussinessException("滚去登陆！");
        }
    }
}
